/*
 * 全局配置变量
 */
server_url = "http://localhost:6520/";
/*
 * url-query解析器
 */
(function() {
	function QueryString(url) {
		if (!(this instanceof QueryString)) {
			return new QueryString(url)
		}
		this.init(url);
	};
	QueryString.prototype = {
		init: function(url) {
			url || (url = location.search);
			var queryStr = url.substr(url.indexOf("?") + 1);
			this._init_queryStr(queryStr);
		},
		_init_queryStr: function(queryStr) {
			var queryList = queryStr.split("&");
			var queryHash = {};
			for (var i = 0, queryInfo, len = queryList.length; i < len; i += 1) {
				if (queryInfo = queryList[i]) {
					queryInfo = queryInfo.split("=");
					if (queryInfo[1]) {
						queryHash[queryInfo[0]] = decodeURIComponent(queryInfo[1]);
					}
				}
			}
			this.queryHash = queryHash;
		},
		get: function(key) {
			var queryHash = this.queryHash || {};
			return queryHash[key];
		},
		set: function(key, value) {
			var queryHash = this.queryHash || (this.queryHash = {});
			queryHash[key] = value;
		},
		toSting: function(origin) {
			origin || (origin = location.origin);
			var queryHash = this.queryHash || {};
			var queryStr = "";
			for (var key in queryHash) {
				if (queryHash.hasOwnProperty(key)) {
					queryStr += (key + "=" + encodeURIComponent(queryHash[key]));
				}
			}
			var url = origin + "?" + queryStr;
		}
	}
	window.QueryString = QueryString;
}());
/*
 * 事件管理器
 */
(function() {
	var _eventCache = {};
	var _eventMap = {};
	var eventManager = {
		is: function(check_obj, eventName, handle, rejectHandle) {
			if (check_obj) {
				handle();
			} else {
				eventManager.on(eventName, handle, rejectHandle);
			}
		},
		on: function(eventName, handle, rejectHandle) {
			var eventList = _eventCache[eventName] || (_eventCache[eventName] = []);
			var _id = Math.random().toString(36).substring(2);
			eventList.push(_eventMap[_id] = {
				_id: _id,
				handle: handle,
				rejectHandle: rejectHandle
			});
			return _id;
		},
		off: function(eventName, _id) {
			if (arguments.length === 1) {
				_id = eventName;
				var eventObj = _eventMap[_id];
				eventObj.handle = null;
			} else if (_eventCache.hasOwnProperty(eventName)) {
				var eventList = _eventCache[eventName];
				for (var i = 0, eventObj; eventObj = eventList[i]; i += 1) {
					if (eventObj._id == _id) {
						eventObj.handle = null;
						eventObj.rejectHandle = null;
					}
				}
			}
		},
		fire: function(eventName) {
			var args = Array.prototype.slice.call(arguments, 1);
			if (_eventCache.hasOwnProperty(eventName)) {
				var eventList = _eventCache[eventName];
				for (var i = 0, eventObj; eventObj = eventList[i]; i += 1) {
					eventObj.handle && eventObj.handle.apply(eventObj, args);
				}
			}
		},
		reject: function(eventName) {
			if (_eventCache.hasOwnProperty(eventName)) {
				var eventList = _eventCache[eventName];
				for (var i = 0, eventObj; eventObj = eventList[i]; i += 1) {
					eventObj.rejectHandle && eventObj.rejectHandle.apply(eventObj, args);
				}
			}
		},
		clear: function(eventName) {
			if (_eventCache.hasOwnProperty(eventName)) {
				var eventList = _eventCache[eventName];
				for (var i = 0, eventObj; eventObj = eventList[i]; i += 1) {
					_eventMap[eventObj._id] = null;
				}
				eventList.length = 0;
			}
		}
	};
	eventManager.emit = eventManager.fire;
	eventManager._eventCache = _eventCache;
	eventManager._eventMap = _eventMap;
	window.eventManager = eventManager;
}());
/*
 * 数据核心工具，用于处理数据
 */
(function() {

	/*
	 * 数据解析工具
	 */
	var dataFormat = function(success, error) {
		error || (error = function(errorMsg, errorCode, xhr) {
			console.error("coAjax Error:", "[" + errorCode + "]", errorMsg);
		});
		return function(data, textStatus, jqXHR) {
			switch (data.type) {
				case "json":
					try {
						var result = $.parseJSON(data.toString);
					} catch (e) {
						data.error = e;
						error.call(this, "JSON Parse Error" /*解析错误*/ , jqXHR);
						return;
					}
					data.result = result;
					success.apply(this, arguments);
					break;
				case "html":
					data.result = jQuery(data.toString);
					success.apply(this, arguments);
					break;
				case "template":
					data.result = jSouper.parse(data.toString);
					success.apply(this, arguments);
					break;
				case "error":
					// data.error = result;
					var result = $.parseJSON(data.toString);
					error.call(this, result.errorMsg, result.errorCode, jqXHR, data)
					break;
				default: //JSON without error
					try {
						var result = $.parseJSON(data.toString);
					} catch (e) {}
					data.result = result;
					success.apply(this, arguments);
					break;
			}
		}
	};

	/*
	 * 基于jQ的跨域ajax工具函数
	 */
	//进度条的注入
	//is onprogress supported by browser?
	var hasOnProgress = ("onprogress" in $.ajaxSettings.xhr());

	//If not supported, do nothing
	if (hasOnProgress) {
		//patch ajax settings to call a progress callback
		$.ajaxSettings.xhr_bak = $.ajaxSettings.xhr;
		$.ajaxSettings.xhr = function() {
			var xhr = $.ajaxSettings.xhr_bak();
			if (this.progress) {
				if (xhr instanceof window.XMLHttpRequest) {
					xhr.addEventListener('progress', this.progress, false);
				}

				if (xhr.upload) {
					xhr.upload.addEventListener('progress', this.progress, false);
				}
			}
			return xhr;
		};
	}

	var ajax = {
		_addCookiesInUrl: function(url) {
			// if(url.indexOf("?")==-1){
			// 	url+="?"
			// }else{
			// 	url+="&"
			// }
			// url += "cors_cookie="+encodeURI(document.cookie);
			return url;
		},
		_ajax: function(url, type, data, success, error, net_error) {
			var jqxhr = $.ajax({
				url: url,
				type: type,
				data: data,
				success: dataFormat(success, error),
				error: net_error,
				progress: function(event) {
					jqxhr.emit("progress", event);
					if (event.loaded == event.total) {
						//释放内存
						eventManager.clear("progress" + _event_prefix);
					}
				},
				xhrFields: {
					withCredentials: true
				}
			});
			var _event_prefix = Math.random();
			//事件机制，目前支持progress
			jqxhr.on = function(eventName) {
				eventName += _event_prefix;
				arguments[0] = eventName;
				return eventManager.on.apply(eventManager, arguments);
			};
			jqxhr.emit = function(eventName) {
				eventName += _event_prefix;
				arguments[0] = eventName;
				return eventManager.fire.apply(eventManager, arguments);
			};
			return jqxhr;
		},
		get: function(url, data, success, error, net_error) {
			url = ajax._addCookiesInUrl(url);
			if (data instanceof Function) {
				net_error = error;
				error = success;
				success = data;
				data = {};
			};
			return ajax._ajax(url, "get", data, success, error, net_error);
		},
		post: function(url, data, success, error, net_error) {
			url = ajax._addCookiesInUrl(url);
			if (data instanceof Function) {
				net_error = error;
				error = success;
				success = data;
				data = {};
			};
			return ajax._ajax(url, "post", data, success, error, net_error);
		},
		put: function(url, data, success, error, net_error) {
			if (data instanceof Function) {
				net_error = error;
				error = success;
				success = data;
				data = {};
			};
			url = ajax._addCookiesInUrl(url);
			return ajax._ajax(url, "put", data, success, error, net_error);
		},
		"delete": function(url, data, success, error, net_error) {
			url = ajax._addCookiesInUrl(url);
			if (data instanceof Function) {
				net_error = error;
				error = success;
				success = data;
				data = {};
			};
			return ajax._ajax(url, "delete", data, success, error, net_error);
		}
	};
	window.coAjax = ajax;
}());
/*
 * 系统对话框的二次封装
 */
// (function() {
// 	var _confirm = window.confirm;
// 	window.native_confirm = _confirm;
// 	window.confirm = function(str, true_cb, false_cb) {
// 		var res = _confirm(str)
// 		if (res) {
// 			true_cb && true_cb();
// 		} else {
// 			false_cb && false_cb();
// 		}
// 	}
// }());
/*
 * 应用程序启动
 */
jSouper.ready(function() {
	//初始化应用程序
	jSouper.app({
		Id: "jSouperApp"
	});

	//事件注册器
	var _events = routie._events = {};
	routie.on = function(pagename, cb) {
		var callbacks = _events[pagename] || (_events[pagename] = []);
		callbacks.push(cb);
		if (pagename === routie._current_page) {
			cb.call(null, routie._current_location)
		}
	};
	routie.emit = function(pagename) {
		var callbacks = _events[pagename];
		if (callbacks && callbacks.length) {
			var args = Array.prototype.slice.call(arguments, 1);
			jSouper.forEach(callbacks, function(cb) {
				cb.apply(null, args);
			});
		}
	};
	//通用跳转器
	routie.jump = function(pagename) {
		location.hash = pagename;
	};
	//通用路由模块，与jSouper进行耦合
	routie.jSouperRoute = function(options) {
		var _viewModules = routie.jSouperRoute._VMS; //VM缓存区
		var base_HTML_url = options.html || "/pages/"; //请求HTML的路径
		var base_js_url = options.js || "/js/pages/"; //请求js文件的路径
		var base_hash_url = options.hash || "!/pages/"; //URL HASH的前缀
		var tele_name = options.tel || "main"; //VM置放的锚点
		var href = options.href;
		var current_vm = options.vm || App;
		var index = ~~options.index || 0;

		var pathname = href;
		var hash_index = pathname.indexOf("#");
		var hash = "";
		if (hash_index !== -1) {
			hash = pathname.substr(hash_index);
			pathname = pathname.substr(0, hash_index);
		}
		var search_index = pathname.indexOf("?");
		var search = "";
		if (search_index !== -1) {
			search = pathname.substr(search_index);
			pathname = pathname.substr(0, search_index);
		}

		if (base_hash_url.substr(-1) !== "/") { //end with "/"
			console.warn("jSouperRoute hash 必须以'/'结尾");
			base_hash_url += "/";
		}
		var pagename_reg = new RegExp("^" + base_hash_url.substr(0, base_hash_url.length - 1) + "(/)?");

		var pagename = jSouper.$.stf(pathname.replace(pagename_reg, ""), "/") || options.default_pagename || "index" //二级页面名

		function _teleporter_vm() {
			current_vm.teleporter(rightVM, tele_name);
			routie._current_page = base_hash_url + pagename;
			var _current_location = routie._current_location || (routie._current_location = {
				pagename: []
			});
			_current_location.pagename[index] = pagename;
			_current_location.pagename.length = index + 1;
			_current_location.pathname = pathname;
			_current_location.hash = hash;
			_current_location.search = search;
			_current_location.href = href;
		};
		var xmp_url = base_HTML_url + pagename + ".html";
		var rightVM = _viewModules[xmp_url];
		if (!rightVM) {
			$.get(xmp_url).done(function(html) {
				_viewModules[xmp_url] = rightVM = jSouper.parse(html, xmp_url)(current_vm.getModel());
				_teleporter_vm();
				$.getScript(base_js_url + pagename + ".js");
			});
		} else {
			_teleporter_vm();
			routie.emit(routie._current_page, routie._current_location);
		}
	};
	routie.jSouperRoute._VMS = {};
	//路由启动器
	routie({
		'!/pages/*': function(args) {
			//一级路由
			routie.jSouperRoute({
				href: "!/pages/" + args,
				html: "/pages/admin/",
				js: "/js/pages/admin/",
				hash: "!/pages/",
				tel: "main",
				default_pagename: "main",
				index: 0,
				vm: App
			});
		}
	});
	if (!location.hash) {
		location.href = "#!/pages/main";
	};
	// jSouper
	// 滚动事件隐藏顶部
	$(window).scroll(function() {
		if ($(window).scrollTop() > 0) {
			$(".top1").addClass("focus");
		} else {
			$(".top1").removeClass("focus");
		};
	});
	$(function() {
		if (!$.cookie("loginer")) {
			location.href = "login.html";
		}
	});
	var loginer = eval("(" + $.cookie("loginer") + ")");
	App.set("loginer", eval("(" + $.cookie("loginer") + ")"));
	App.set("loginer.address", eval("(" + loginer.address + ")"));
	App.set("loginer.createtime", new Date(loginer.createtime).toLocaleString());
	App.set("logintype", $.cookie("logintype"));

});